package com.darren.befriend.adapters;

import java.util.ArrayList;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.darren.befriend.BaseActivity;
import com.darren.befriend.HomeActivity;
import com.darren.befriend.R;
import com.darren.befriend.utilities.ParseUtility;
import com.darren.befriend.views.CircleImageView;
import com.darren.befriend.views.HelveticaLTStdLight;
import com.parse.ParseObject;
import com.parse.ParseUser;

/**
 * 
 * @author DuongThoai
 * 
 */
public class FriendsAdapter extends BaseAdapter {

	private Context mContext;
	private ArrayList<ParseUser> mFriendtArr;
	private ParseUser mFriend;
	private ArrayList<String> mSentRequests;
	private ArrayList<ParseObject> mRequests;
	private onDeleteListener listener;
	private int mScreenWidth;
	private RelativeLayout mCurrentItem;
	private OpenItemListener openListener;
	private int action_down_x = 0;
	private int action_up_x = 0;
	private int difference = 0;

	public FriendsAdapter(Context c, ArrayList<ParseUser> friendArr,
			ArrayList<String> sentRequests, ArrayList<ParseObject> requests,
			int screenWidth) {
		mContext = c;
		mFriendtArr = friendArr;
		mSentRequests = sentRequests;
		this.mRequests = requests;
		this.mScreenWidth = screenWidth;
	}

	public void setOpenListener(OpenItemListener openListener) {
		this.openListener = openListener;
	}

	public void setDeleteListener(onDeleteListener listener) {
		this.listener = listener;
	}

	@Override
	public int getCount() {

		if (mFriendtArr != null) {

			return mFriendtArr.size();
		}

		return 0;
	}

	@Override
	public Object getItem(int arg0) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public int getItemViewType(int position) {
		return 0;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		InterestHolder holder;
		mFriend = mFriendtArr.get(position);
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) mContext
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = (ViewGroup) inflater.inflate(
					R.layout.friend_item_layout, parent, false);
			holder = new InterestHolder();
			holder.friendName = (HelveticaLTStdLight) convertView
					.findViewById(R.id.friend_name);
			holder.profileImg = (CircleImageView) convertView
					.findViewById(R.id.friend_icon);
			holder.status = (HelveticaLTStdLight) convertView
					.findViewById(R.id.friend_status);
			holder.deleteBtn = (TextView) convertView.findViewById(R.id.delete);
			holder.exclaimationImg = (ImageView) convertView
					.findViewById(R.id.exclamination_img);
			holder.userLayout = (RelativeLayout) convertView
					.findViewById(R.id.friend_item_front);
			convertView.setTag(holder);
		} else {

			holder = (InterestHolder) convertView.getTag();
		}

		// profile img
		String currentFullName = mFriend.get("fullName").toString();
		if (!currentFullName.contains("_local")) {
			String url = String
					.format(mContext.getResources().getString(
							R.string.profile_normal_url), mFriend.getUsername());
			((BaseActivity) mContext).getImageLoader().displayImage(url,
					holder.profileImg, ((BaseActivity) mContext).getOptions());
		} else {

			try {

				byte[] image = (byte[]) mFriend.get("Photo");
				Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0,
						image.length);
				holder.profileImg.setImageBitmap(bitmap);
			} catch (Exception e) {

				holder.profileImg.setImageResource(R.drawable.tmp_full_pic);
			}
		}

		// name
		String fullName = ParseUtility.getFullName(mFriend);
		if (fullName.contains("_local")) {

			holder.friendName.setText(fullName.replace("_local", ""));
		} else {

			holder.friendName.setText(fullName);
		}

		// status
		if (ParseUtility.getStatus(mFriend)) {

			holder.status.setText(mContext.getString(R.string.online_text));
			holder.status.setTextColor(Color.parseColor("#333333"));
			holder.friendName.setTextColor(Color.parseColor("#333333"));
		} else {

			holder.status.setText(mContext.getString(R.string.offline_text));
			holder.status.setTextColor(Color.parseColor("#999999"));
			holder.friendName.setTextColor(Color.parseColor("#999999"));
		}

		if (mRequests != null) {

			if (position < mRequests.size()) {

				holder.exclaimationImg.setVisibility(View.VISIBLE);
			} else {

				boolean isSent = false;
				for (String name : mSentRequests) {
					if (mFriend.getUsername().equals(name)) {
						isSent = true;
						break;
					}
				}

				if (isSent) {

					holder.exclaimationImg
							.setImageResource(R.drawable.icon_question);
					holder.exclaimationImg.setVisibility(View.VISIBLE);
				} else {

					holder.exclaimationImg.setVisibility(View.INVISIBLE);
				}
			}
		} else {

			boolean isSent = false;
			for (String name : mSentRequests) {
				if (mFriend.getUsername().equals(name)) {
					isSent = true;
					break;
				}
			}

			if (isSent) {

				holder.exclaimationImg
						.setImageResource(R.drawable.icon_question);
				holder.exclaimationImg.setVisibility(View.VISIBLE);
			} else {

				holder.exclaimationImg.setVisibility(View.INVISIBLE);
			}

		}

		holder.deleteBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (listener != null) {
					listener.onDelete(position);
				}
			}
		});

		MyTouchListener onTouchListener = new MyTouchListener(position);
		holder.userLayout.setOnTouchListener(onTouchListener);
		LayoutParams params = (LayoutParams) holder.userLayout
				.getLayoutParams();
		params.width = mScreenWidth;
		holder.userLayout.setLayoutParams(params);
		return convertView;
	}

	static class InterestHolder {
		com.darren.befriend.views.CircleImageView profileImg;
		HelveticaLTStdLight friendName;
		HelveticaLTStdLight status;
		RelativeLayout userLayout;
		TextView deleteBtn;
		ImageView exclaimationImg;
	}

	public interface onDeleteListener {
		public void onDelete(int position);
	}

	public interface OpenItemListener {
		public void onOpen(int position);
	}

	class MyTouchListener implements OnTouchListener {

		private int position;

		/**
		 * 
		 */
		public MyTouchListener(int pos) {
			// TODO Auto-generated constructor stub
			this.position = pos;
		}

		@Override
		public boolean onTouch(View v, MotionEvent event) {

			// InterestHolder holder = (InterestHolder) v.getTag();
			int action = event.getAction();
			// int position = (Integer) v.getTag();

			switch (action) {
			case MotionEvent.ACTION_DOWN:

				action_down_x = (int) event.getX();
				break;
			case MotionEvent.ACTION_UP:

				action_up_x = (int) event.getX();
				difference = action_down_x - action_up_x;
				calcuateDifference(v, position);
				break;
			}

			return true;
		}
	}

	private void calcuateDifference(final View holder, final int position) {

		((HomeActivity) mContext).runOnUiThread(new Runnable() {

			@Override
			public void run() {

				float px = TypedValue.applyDimension(
						TypedValue.COMPLEX_UNIT_DIP, 90, mContext
								.getResources().getDisplayMetrics());
				if (difference == 0) {

					openListener.onOpen(position);
				} else if (difference > 75) {

					ObjectAnimator animator;
					if (mCurrentItem != null) {

						animator = ObjectAnimator.ofFloat(mCurrentItem,
								"translationX", 0);
						animator.setDuration(200);
						animator.start();
					}

					animator = ObjectAnimator.ofFloat(holder, "translationX",
							0 - px);
					animator.setDuration(200);
					animator.start();
					mCurrentItem = (RelativeLayout) holder;
				} else if (difference < -75) {

					ObjectAnimator animator = ObjectAnimator.ofFloat(holder,
							"translationX", 0);
					animator.setDuration(200);
					animator.start();
				}

				action_down_x = 0;
				action_up_x = 0;
				difference = 0;
			}
		});
	}

}
